package com.green.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.green.system.common.ActiveUser;
import com.green.system.common.Constant;
import com.green.system.common.MenuTreeNode;
import com.green.system.common.ResultObj;
import com.green.system.domain.Loginfo;
import com.green.system.domain.Menu;
import com.green.system.domain.User;
import com.green.system.service.LoginfoService;
import com.green.system.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Green
 * @Date: 2021/10/18/9:05
 * @Description:
 */

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private MenuService menuService ;

    @Autowired
    private LoginfoService loginfoService ;

    @Autowired
    private StringRedisTemplate redisTemplate ;

    /**
    * @Description: 登录
    * @Param: [loginname, password]
    * @return: com.green.system.common.ResultObj
    * @Author: Green
    * @Date: 2021/10/19
    */
    
    @RequestMapping("doLogin")
    @ResponseBody
    public ResultObj doLogin(String loginname, String password,  HttpServletRequest request){ //String keyCode, String captcha,
        try{

                    Subject subject = SecurityUtils.getSubject();
                    UsernamePasswordToken loginToken = new UsernamePasswordToken(loginname,password);
                    subject.login(loginToken);
                    //ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
                    //得到shiro的sessionID == token
                    String token =subject.getSession().getId().toString();
                    //写入登录日志
                    ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
                    User user = activeUser.getUser();
                    Loginfo loginfo = new Loginfo();
                    loginfo.setLoginname(user.getName()+"-"+user.getLoginname());
                    loginfo.setLoginip(request.getRemoteAddr());
                    loginfo.setLogintime(new Date());
                    loginfoService.save(loginfo);
                    List<String> permissions=activeUser.getPermissions();
                    Map<String,Object> map = new HashMap<>();
                    map.put("token",token);
                    map.put("permissions",permissions);
                    map.put("usertype",user.getType());
                    map.put("username",user.getName());

                    return new ResultObj(200,"登录成功",map);

        }catch (AuthenticationException e){
            e.printStackTrace();
            return new ResultObj(-1,"用户或密码不正确");
        }
    }
    
    /**
    * @Description: 验证码检查
    * @Param: 
    * @return: redis key value
    * @Author: Green
    * @Date: 2021/10/19
    */
/*    @RequestMapping("captcha")
    public void captcha(HttpServletResponse response, String codeKey) throws IOException{
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100,38,4,4);
        String code = captcha.getCode();
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(codeKey, code);
        opsForValue.getOperations().expire(codeKey, 60, TimeUnit.SECONDS);
        captcha.write(response.getOutputStream());
    }*/


    /**
     * 加载所有菜单[顶部菜单和左侧菜单]
     * @return
     */
    @RequestMapping("loadIndexMenu")
    @ResponseBody
    public Object loadIndexMenu(){
        //得到当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
        User user = activeUser.getUser();
        if (null == user){
            return null ;
        }

        List<Menu> menus= null ;

        if (user.getType().equals(Constant.USER_TYPE_SUPER)){
            //超级管理员
            menus=menuService.queryAllMenuForList();
        }else{
            //普通用户
            menus=menuService.queryMenusForListByUserId(user.getId());
        }

        //构造菜单树
        List<MenuTreeNode> treeNodes = new ArrayList<>();
        for (Menu menu: menus) {
            Boolean spread = menu.getSpread()==Constant.SPREAD_TRUE?true:false;
            treeNodes.add(new MenuTreeNode(menu.getId(),menu.getPid(),menu.getTitle(),menu.getHref(),menu.getIcon(),spread,menu.getTarget(),menu.getTypecode()));
        }

        //先双重循环构造树
        List<MenuTreeNode> nodes = MenuTreeNode.MenuTreeNodeBuilder.build(treeNodes,0);
        //构造键值对达成菜单格式
        Map<String,Object> res= new HashMap<>();
        for (MenuTreeNode n : nodes) {
            res.put(n.getTypecode(),n);
        }
        //针对菜单init格式还需要再套一个menuInfo的键值对
        Map<String,Object> res1 = new HashMap<>();
        res1.put("menuInfo",res);

        //去除空值child=[]防止菜单错误
        return res1;

    }

    /**
     * 验证当前token是否登录
     */
    @RequestMapping("checkLogin")
    @ResponseBody
    public ResultObj checkLogin(){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            return ResultObj.IS_LOGIN;
        }else
            return ResultObj.UN_LOGIN;
    }

}
